package com.test.browser;

import com.sun.org.apache.bcel.internal.ExceptionConstants;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Reporter;

public class BasePage {
    private Logger log = Logger.getLogger(Package.class);

    private WebDriver driver;

    public BasePage(WebDriver driver) {
        this.driver = driver;
    }

    /**
     * 进入网址
     * @param url
     */
    public void open(String url){
        driver.get(url);
    }

    /**
     * 封装显示等待
     * @param by
     * @return
     */
    public WebElement waitElementVisibility(By by){
        WebElement element = null;
        try{
            // 5秒元素可见显式等待
            WebDriverWait wait = new WebDriverWait(driver, 5);
            element = wait.until(ExpectedConditions.visibilityOfElementLocated(by));
            return element;
        }catch (Exception e){
            log.error("元素定位异常" + e.getMessage());
        }
        return element;
    }

    /**
     * 输入文本
     * @param by
     * @param text
     */
    public void sendKeys(By by, String text){
        WebElement element = waitElementVisibility(by);
        if(element!=null){
            element.clear();
            element.sendKeys(text);
            log.info("元素："+ by+",输入："+ text);
            Reporter.log("元素："+ by+",输入："+ text);
        }
    }

    /**
     * 点击元素
     * @param by
     */
    public void click(By by){
        WebElement element = waitElementVisibility(by);
        if(element!=null){
            element.click();
            log.info("点击元素："+ by);
            Reporter.log("点击元素："+ by);
        }
    }

    /**
     * 判断元素是否可见
     * @param by
     * @return
     */
    public boolean isDisplayed(By by){
        WebElement element = waitElementVisibility(by);
        if(element != null){
            return element.isDisplayed();
        }
        return false;
    }

    /**
     * 获取元素文本
     * @param by
     * @return
     */
    public String getText(By by){
        WebElement element = waitElementVisibility(by);
        if(element!=null){
            return element.getText();
        }
        return "";
    }

    /**
     * 关闭浏览器
     */
    public void close(){
        driver.close();
    }
}
